package Dao;

import Table.Book;
import Utils.DruidUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class FindByPageDao {
    //统计总记录
    public static int findTotalCount() {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        int totalCount = 0;
        try {
            conn = DruidUtils.getConnection();
            String sql = "select count(*) from book";
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                totalCount = rs.getInt(1);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            DruidUtils.close(rs, pstmt, conn);
        }
        return totalCount;
    }

    public static ArrayList<Book> findByPage(int start, int rows) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        ArrayList<Book> list = new ArrayList<>();
        try {
            conn = DruidUtils.getConnection();
            String sql = "select * from book limit ?,?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, start);
            pstmt.setInt(2, rows);
            rs = pstmt.executeQuery();
            while (rs.next()) {
                Book book = new Book();
                book.setId(rs.getInt("id"));
                book.setBookname(rs.getString("bookname"));
                book.setAuther(rs.getString("auther"));
                book.setPrice(rs.getInt("price"));
                book.setNums(rs.getInt("nums"));
                list.add(book);
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            DruidUtils.close(rs, pstmt, conn);
        }
        return list;
    }
}
